<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="课程名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入课程名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="课程类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="课程类型" clearable style="width: 130px">
                    <el-option label="游泳类" value="1" />
                    <el-option label="舞蹈类" value="2" />
                    <el-option label="拳击类" value="3" />
                </el-select>
            </el-form-item>
            <el-form-item label="适用人群" prop="applyTo">
                <el-select v-model="queryParams.applyTo" placeholder="适用人群" clearable style="width: 130px">
                    <el-option label="中小学生" value="1" />
                    <el-option label="上班族" value="2" />
                    <el-option label="小白用户" value="3" />
                    <el-option label="健身达人" value="4" />
                </el-select>
            </el-form-item>
            <el-form-item label="最低价格" prop="minPrice">
                <el-input-number v-model="queryParams.minPrice" :min="0" :step="100" :precision="2" placeholder="最低价格" style="width: 150px" />
            </el-form-item>
            <el-form-item label="最高价格" prop="maxPrice">
                <el-input-number v-model="queryParams.maxPrice" :min="0" :step="100" :precision="2" placeholder="最高价格" style="width: 150px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="课程编号" align="center" prop="courseId" />
            <el-table-column label="课程类型" align="center">
                <template #default="scope">
                    <el-tag v-if="getCourseTypeLabel(scope.row.courseType)" :type="getCourseTypeTagType(scope.row.courseType)">
                        {{ getCourseTypeLabel(scope.row.courseType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="课程名称" align="center" prop="courseName" />
            <el-table-column label="课程价格" align="center" prop="coursePrice">
                <template #default="scope">
                    <span>¥{{ scope.row.coursePrice }}</span>
                </template>
            </el-table-column>
            <el-table-column label="课程适用人群" align="center">
                <template #default="scope">
                    <el-tag v-if="getApplicableAudienceLabel(scope.row.applicableAudience)" :type="getApplicableAudienceTagType(scope.row.applicableAudience)">
                        {{ getApplicableAudienceLabel(scope.row.applicableAudience) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="课程简介" align="center" prop="courseIntro" show-overflow-tooltip />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改课程对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="courseRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="课程名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入课程名称" maxlength="50" show-word-limit />
                </el-form-item>
                <el-form-item label="课程类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择课程类型" clearable style="width: 100%">
                        <el-option label="游泳类" value="1" />
                        <el-option label="舞蹈类" value="2" />
                        <el-option label="拳击类" value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="课程价格" prop="price">
                    <el-input-number v-model="form.price" :min="0" :precision="2" :step="100" placeholder="请输入课程价格" style="width: 100%" />
                </el-form-item>
                <el-form-item label="适用人群" prop="applyTo">
                    <el-select v-model="form.applyTo" placeholder="请选择适用人群" clearable style="width: 100%">
                        <el-option label="中小学生" value="1" />
                        <el-option label="上班族" value="2" />
                        <el-option label="小白用户" value="3" />
                        <el-option label="健身达人" value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="课程简介" prop="info">
                    <el-input v-model="form.info" type="textarea" placeholder="请输入课程简介" :rows="4" maxlength="200" show-word-limit />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import RightToolbar from '@/components/RightToolbar/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listCourse, getCourse, delCourse, addCourse, updateCourse, exportCourse } from "@/api/tienchin/course";

const { proxy } = getCurrentInstance();

const courseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 课程类型映射
const courseTypeMap = {
    1: "游泳类",
    2: "舞蹈类", 
    3: "拳击类"
};

// 适用人群映射
const applicableAudienceMap = {
    1: "中小学生",
    2: "上班族",
    3: "小白用户",
    4: "健身达人"
};

// 课程类型标签样式映射
const courseTypeTagTypeMap = {
    1: "",
    2: "info",
    3: "warning"
};

// 适用人群标签样式映射
const applicableAudienceTagTypeMap = {
    1: "warning",
    2: "info", 
    3: "success",
    4: "danger"
};

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        type: undefined,
        applyTo: undefined,
        minPrice: undefined,
        maxPrice: undefined,
    },
    rules: {
        name: [
            { required: true, message: "课程名称不能为空", trigger: "blur" },
            { min: 1, max: 50, message: "课程名称长度在 1 到 50 个字符", trigger: "blur" }
        ],
        type: [
            { required: true, message: "课程类型不能为空", trigger: "change" }
        ],
        price: [
            { required: true, message: "课程价格不能为空", trigger: "blur" },
            { type: "number", min: 0, message: "课程价格必须大于等于0", trigger: "blur" }
        ],
        applyTo: [
            { required: true, message: "适用人群不能为空", trigger: "change" }
        ],
        info: [
            { max: 200, message: "课程简介长度不能超过200个字符", trigger: "blur" }
        ]
    }
});

const { queryParams, form, rules } = toRefs(data);

// 获取课程类型标签
function getCourseTypeLabel(type) {
    return courseTypeMap[type] || "";
}

// 获取课程类型标签样式
function getCourseTypeTagType(type) {
    return courseTypeTagTypeMap[type] || "";
}

// 获取适用人群标签
function getApplicableAudienceLabel(audience) {
    return applicableAudienceMap[audience] || "";
}

// 获取适用人群标签样式
function getApplicableAudienceTagType(audience) {
    return applicableAudienceTagTypeMap[audience] || "";
}

/** 查询课程列表 */
function getList() {
    loading.value = true;
    // 构建查询参数，确保字段名与后端接口一致
    const params = {
        pageNum: queryParams.value.pageNum,
        pageSize: queryParams.value.pageSize,
        name: queryParams.value.name,
        type: queryParams.value.type,
        applyTo: queryParams.value.applyTo,
        minPrice: queryParams.value.minPrice,
        maxPrice: queryParams.value.maxPrice,
    };
    
    listCourse(params).then(response => {
        courseList.value = response.rows.map(item => ({
            courseId: item.courseId,
            courseType: item.type,
            courseName: item.name,
            coursePrice: item.price,
            applicableAudience: item.applyTo,
            courseIntro: item.info,
            createTime: item.createTime,
        }));
        total.value = response.total;
        loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    queryParams.value.pageNum = 1;
    getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.courseId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加课程";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const courseId = row.courseId || ids.value;
    getCourse(courseId).then(response => {
        // 确保数据格式正确，与后端接口字段名保持一致
        form.value = {
            courseId: response.data.courseId,
            name: response.data.name,
            type: response.data.type ? String(response.data.type) : null,
            price: response.data.price,
            applyTo: response.data.applyTo ? String(response.data.applyTo) : null,
            info: response.data.info,
        };
        open.value = true;
        title.value = "修改课程";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["courseRef"].validate(valid => {
        if (valid) {
            // 构建提交数据，确保字段名与后端接口一致
            const submitData = {
                courseId: form.value.courseId,
                name: form.value.name,
                type: form.value.type,
                price: form.value.price,
                applyTo: form.value.applyTo,
                info: form.value.info,
            };
            
            if (form.value.courseId != null) {
                updateCourse(submitData).then(response => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addCourse(submitData).then(response => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

/** 表单重置 */
function reset() {
    form.value = {
        courseId: null,
        name: null,
        type: null,
        price: null,
        applyTo: null,
        info: null
    };
    proxy.resetForm("courseRef");
}

/** 删除按钮操作 */
function handleDelete(row) {
    const courseIds = row.courseId || ids.value;
    ElMessageBox.confirm('是否确认删除课程编号为"' + courseIds + '"的数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    }).then(function () {
        return delCourse(courseIds);
    }).then(() => {
        getList();
        ElMessage.success("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    // 构建导出参数，确保字段名与后端接口一致
    const exportParams = {
        pageNum: queryParams.value.pageNum,
        pageSize: queryParams.value.pageSize,
        name: queryParams.value.name,
        type: queryParams.value.type,
        applyTo: queryParams.value.applyTo,
        minPrice: queryParams.value.minPrice,
        maxPrice: queryParams.value.maxPrice,
    };
    
    // 使用download方法进行文件下载
    proxy.download("tienchin/course/export", exportParams, `course_${new Date().getTime()}.xlsx`);
}

getList();
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
}
.el-form-item {
    margin-bottom: 18px;
}
.el-tag {
    margin-right: 5px;
}
</style>